/**
 * 流式响应处理
 */
import { EventEmitter } from 'events';

/**
 * 流式响应处理类
 * 处理通义千问API的流式响应
 */
export class StreamResponse {
  private reader: ReadableStreamDefaultReader<Uint8Array>;
  private decoder: TextDecoder = new TextDecoder();
  private buffer: string = '';
  private eventEmitter: EventEmitter = new EventEmitter();
  private isProcessing: boolean = false;
  private textContent: string = '';
  private imageUrls: string[] = [];
  private errorMessage: string | null = null;
  private isDone: boolean = false;

  /**
   * 创建流式响应处理器
   * @param stream 可读流
   */
  constructor(stream: ReadableStream<Uint8Array>) {
    this.reader = stream.getReader();
    this.processStream();
  }

  /**
   * 处理流式响应
   */
  private async processStream(): Promise<void> {
    if (this.isProcessing) return;
    
    this.isProcessing = true;
    
    try {
      while (true) {
        const { done, value } = await this.reader.read();
        
        if (done) {
          this.isDone = true;
          this.eventEmitter.emit('end');
          break;
        }
        
        const chunk = this.decoder.decode(value, { stream: true });
        this.buffer += chunk;
        
        // 处理类SSE格式的响应
        const lines = this.buffer.split('\n\n');
        this.buffer = lines.pop() || '';
        
        for (const line of lines) {
          if (line.trim() === '') continue;
          
          try {
            if (line.startsWith('data: ')) {
              const jsonStr = line.slice(6);
              if (jsonStr.trim() === '[DONE]') {
                this.isDone = true;
                this.eventEmitter.emit('end');
                continue;
              }
              
              const data = JSON.parse(jsonStr);
              this.processResponseData(data);
            }
          } catch (e) {
            console.error('Error parsing stream data:', e);
          }
        }
      }
    } catch (e) {
      this.errorMessage = (e as Error).message;
      this.eventEmitter.emit('error', e);
    } finally {
      this.isProcessing = false;
    }
  }

  /**
   * 处理响应数据
   * @param data 响应数据
   */
  private processResponseData(data: any): void {
    // 处理阿里通义千问格式的响应
    if (data.output && data.output.choices && data.output.choices.length > 0) {
      const choice = data.output.choices[0];
      
      if (choice.message && choice.message.content) {
        for (const content of choice.message.content) {
          if (content.type === 'text') {
            this.textContent += content.text;
            this.eventEmitter.emit('text', content.text);
          } else if (content.type === 'image_url') {
            const imageUrl = content.image_url.url;
            this.imageUrls.push(imageUrl);
            this.eventEmitter.emit('image', imageUrl);
          }
        }
      }
    }
  }

  /**
   * 注册文本回调
   * @param callback 回调函数
   */
  onText(callback: (text: string) => void): void {
    this.eventEmitter.on('text', callback);
  }

  /**
   * 注册图像回调
   * @param callback 回调函数
   */
  onImage(callback: (url: string) => void): void {
    this.eventEmitter.on('image', callback);
  }

  /**
   * 注册结束回调
   * @param callback 回调函数
   */
  onEnd(callback: () => void): void {
    // 如果已经结束，直接调用回调
    if (this.isDone) {
      callback();
      return;
    }
    this.eventEmitter.on('end', callback);
  }

  /**
   * 注册错误回调
   * @param callback 回调函数
   */
  onError(callback: (error: Error) => void): void {
    // 如果已经有错误，直接调用回调
    if (this.errorMessage) {
      callback(new Error(this.errorMessage));
      return;
    }
    this.eventEmitter.on('error', callback);
  }

  /**
   * 获取当前累积的文本内容
   */
  getText(): string {
    return this.textContent;
  }

  /**
   * 获取图像URL列表
   */
  getImageUrls(): string[] {
    return [...this.imageUrls];
  }

  /**
   * 检查响应是否完成
   */
  isDone(): boolean {
    return this.isDone;
  }

  /**
   * 取消流式响应处理
   */
  async cancel(): Promise<void> {
    try {
      await this.reader.cancel();
      this.eventEmitter.emit('end');
    } catch (e) {
      console.error('Error cancelling stream:', e);
    }
  }
}